<?php 

//  Pdo_Mysql, Pdo_Pgsql 

$liiiii = 1;
$pdo = $this->_pdo;
//'postgres';
	if ($pdo=='Pdo_Mysql')
	{
		$link =  mysql_connect($this->_server, $this->_username, $this->_password);		
		//$link =  mysql_connect('127.0.0.1', 'root', 'R00T11MP55Q');
		$result = mysql_list_tables($this->_db_name);
	}
	else if ($pdo=='Pdo_Pgsql')
	{		
		$conn_string = 'host=91.121.95.146 port=5432 dbname='.$this->_db_name.' user=dbpostgres password=12534TEREppp00';
		$pg_link = pg_connect ($conn_string);
		$pg_lista_tabel = pg_query($pg_link, 'select tablename from pg_tables where schemaname = \'public\'');
		//var_dump($pg_lista_tabel);
	}
		function createFile2( $file, $content, $p_path )
			{
				$path = $p_path.'/application/models/';;
				if( file_exists($path.$file) )
				{
					unlink($path.$file);
				}
			    touch( $path.$file );
			    chmod($path.$file, 0777);
			    file_put_contents($path.$file, $content);
			}			
			
			
    		function generateModel($table_attrs, $column, $p_path_projekt, $p_szczegoly_kolumn, $p_pdo)
		    {
		
		    	$properties = array();
		    	$fields_list= array();
		    	
		    	$primaryKey = '';
		    	$insd = '';
		    	$insp = '';
		    	$modd = '';
		    	$modp = '';
		    	$fk_licznik = '';
		    	$fk = array();
		    	$referencje_tb = array();
		    	$constrainty_tb = array();
		    	
		    	if (isset($table_attrs['referencje']) )
		    		$referencje_tb = $table_attrs['referencje'];

		    	if (isset($table_attrs['constrainty']) )
		    		$constrainty_tb = $table_attrs['constrainty'];

		    	//print_r($p_szczegoly_kolumn);	
		    	//exit('ble');	
		    	
				foreach( $column as $c )
				{
					//echo $c['name'].'<br>';
					
					array_push($properties,  array('name'  => (string)($table_attrs['name'].'_'.$c['name']), 
												   'const' => true, 
												   'defaultValue' => (string)($table_attrs['name'].'_'.$c['name'])
								) );
					
				    if( isset($c['primaryKey']) )
					{
						$primaryKey = (string)($table_attrs['name'].'_'.$c['primaryKey']);
					}
					if( isset($c['insd']) )
					{
						$insd = (string)($table_attrs['name'].'_'.$c['insd']);
					}
					if( isset($c['insp']) )
					{
						$insp = (string)($table_attrs['name'].'_'.$c['insp']);
					}
					if( isset($c['modd']) )
					{
						$modd = (string)($table_attrs['name'].'_'.$c['modd']);
					}
					if( isset($c['modp']) )
					{
						$modp = (string)($table_attrs['name'].'_'.$c['modp']);
					}	
					
					$tablica_name = explode('_', (string)$c['name']);
					foreach ($tablica_name as $tab_n)
					{
						if 	($tab_n=='fk')
							$fk[] = (string)($table_attrs['name'].'_'.$c['name']);
					}
						
					
					$tab_pom = array();
					
					//print_r($p_szczegoly_kolumn);
					//echo $p_pdo.'<br>';
					if ($pdo=='Pdo_Mysql')
					{
					 	while ($row = mysql_fetch_array($p_szczegoly_kolumn, MYSQL_NUM))
						{							
							$tab_pom = array_merge($tab_pom, array($table_attrs['name'].'_'.$row[0]=>array($row[1],$row[2],$row[3])));
						}	
					}
					else if ($p_pdo=='Pdo_Pgsql')
					{
						for ($j=0; $j < pg_num_rows($p_szczegoly_kolumn); $j++)
			    		{		    	
			    			$pg_column_row = pg_fetch_row($p_szczegoly_kolumn,$j);
			    			$tab_pom = array_merge($tab_pom, array($table_attrs['name'].'_'.$pg_column_row[0]=>array($pg_column_row[1],$pg_column_row[2],$pg_column_row[3])));	
			    		}
						
					}
					
					//print_r($tab_pom);	
					$fields_list = array_merge($fields_list, $tab_pom);
			
				}
				
				if (!empty($referencje_tb))
				{					
					if ($p_pdo=='Pdo_Mysql')
					{
						while ($row = mysql_fetch_array($referencje_tb, MYSQL_NUM))
						{
							$referencje_wynik_tb[] = $row[0];
							$referencje_wynik_tb[] = $row[0].'_'.$row[1];
						}
					}
					else if ($p_pdo=='Pdo_Pgsql')
					{
						$referencje_wynik_tb = array();
						for ($j=0; $j < pg_num_rows($referencje_tb); $j++)
			    		{		    	
			    			$pg_column_row = pg_fetch_row($referencje_tb,$j);
			    			if (!in_array($pg_column_row[2], $referencje_wynik_tb))
			    			{
			    				$referencje_wynik_tb[] = $pg_column_row[2];
			    				$referencje_wynik_tb[] = $pg_column_row[2].'_'.$pg_column_row[3];
			    			}	
			    		}
						//while ($row = pg_fetch_array($referencje_tb, PGSQL_NUM))
						//{
						//	$referencje_wynik_tb[] = $row[0];
						//	$referencje_wynik_tb[] = $row[1];
						//}
					}	
				}
				
		    	if (!empty($constrainty_tb))
				{
					if ($p_pdo=='Pdo_Mysql')
					{
						while ($row = mysql_fetch_array($constrainty_tb, MYSQL_NUM))
						{
							$constrainty_wynik_tb[] = $row[0];
							$constrainty_wynik_tb[] = $row[0].'_'.$row[1];
						}
					}
					else if ($p_pdo=='Pdo_Pgsql')
					{					
						for ($j=0; $j < pg_num_rows($constrainty_tb); $j++)
			    		{		    	
			    			$pg_column_row = pg_fetch_row($constrainty_tb,$j);
			    			$constrainty_wynik_tb[] = $pg_column_row[0];
			    			$constrainty_wynik_tb[] = $pg_column_row[0].'_'.$pg_column_row[1];
			    			$fk[] = (string)($table_attrs['name'].'_'.$pg_column_row[2]);	
			    		}
						//while ($row = pg_fetch_array($constrainty_tb, PGSQL_NUM))
						//{
						//	$constrainty_wynik_tb[] = $row[0];
						//	$constrainty_wynik_tb[] = $row[1];
						//}
					}	
				}
				
				
				# array with fields
				array_push($properties, array('name'  => 'fields_list', 
											  'visibility' => 'public', 
											  'defaultValue' => $fields_list ) );
				
				
				# maper name
				array_push($properties, array('name'  => 'CLASS_name', 
											  'const' => true, 
											  'defaultValue' => (string)$table_attrs['phpName'] ) );
				
				# table name
				array_push($properties, array('name'  => '_name', 
											  'visibility' => 'public', 
											  'defaultValue' => (string)$table_attrs['name'] ) );
				
				# primary key
				if( !empty($primaryKey) )
				{
				array_push($properties, array('name'  => 'PK', 
											  'visibility' => 'public', 
											  'defaultValue' => (string)$primaryKey ) );
				}		
				
				# array z kluczami obcymi
				if( !empty($fk) )
				{
				array_push($properties, array('name'  => 'fk_list', 
											  'visibility' => 'public', 
											  'defaultValue' => $fk ) );
				}
				
				# array z referencjami, para: tabela, kolumna
				if (!empty($referencje_wynik_tb))
				{
				array_push($properties, array('name'  => 'ref_list', 
										  'visibility' => 'public', 
										  'defaultValue' => $referencje_wynik_tb ) );
				}

		    	# array z constraintami, para: tabela, kolumna
				if (!empty($constrainty_wynik_tb))
				{
				array_push($properties, array('name'  => 'const_list', 
										  'visibility' => 'public', 
										  'defaultValue' => $constrainty_wynik_tb ) );
				}				
				
				# insd
				if( !empty($insd) )
				{
				array_push($properties, array('name'  => 'insd', 
											  'visibility' => 'public', 
											  'defaultValue' => (string)$insd ) );
				}			
				
				# insp
				if( !empty($insp) )
				{
				array_push($properties, array('name'  => 'insp', 
											  'visibility' => 'public', 
											  'defaultValue' => (string)$insp ) );
				}					
				
				# modd
				if( !empty($modd) )
				{
				array_push($properties, array('name'  => 'modd', 
											  'visibility' => 'public', 
											  'defaultValue' => (string)$modd ) );
				}
		
				# modp
				if( !empty($modp) )
				{
				array_push($properties, array('name'  => 'modp', 
											  'visibility' => 'public', 
											  'defaultValue' => (string)$modp ) );
				}
				
				array_push($properties, array('name'  => 'nazwy_kolumn', 
											  'visibility' => 'public', 
											  'defaultValue' => '' ) );
				
				$foo      = new Zend_CodeGenerator_Php_Class();
				
				$docblock = new Zend_CodeGenerator_Php_Docblock(array(
				
				    'shortDescription' => 'Klasa mapujaca tabelę `'.$class_name.'`',
				    //'longDescription'  => 'This is a class generated with Zend_CodeGenerator.',
				    'tags'             => array(
				        array(  'name'        => 'version', 'description' => '$Rev:$', ),
				 			),));
		
				
				$foo->setName( ( string ) $table_attrs['phpName'].' extends Zend_Db_Table_Abstract' );
				
				   $foo->setDocblock( $docblock );
				   $foo->setProperties( $properties );
				   $foo->setMethods(array(
				        	array(
				            'name'       => 'selectOne',
				        	'visibility' => 'public',
				            'parameters' => array(
				                array('name' => 'p_id = NULL'),
				                array('name' => 'p_where = array()'),
				            ),
				            
				            'body' =>	'$select = $this->select();'. "\n".
				            			'if (isset($p_id))'."\n".
										'	$select->where($this->renderujkolumny($this->PK).\' like '.'\\'.'\'\'.$p_id.\''.'\\'.'\'\');'."\n\n".
		
										'foreach ($p_where as $variable) {'."\n".
				            			'	$select->where($this->renderujkolumny($variable));'."\n".
				            			'}'.
										'$s = $this->fetchRow( $select );'."\n".
									
										'if ($s!=NULL)'."\n".
										'	return $s->toArray();'."\n".
				            			'else'."\n".
				            			' return $s;',		            
		
				            'docblock'   => new Zend_CodeGenerator_Php_Docblock(array(
				                'longDescription' => 'Metoda pobiera rekord o zadanym id lub tablicy z warunkami klauzuli where.',
				                'tags'            => array(
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Param(array(
				                        'paramName' => 'p_id',
				                        'datatype'  => 'int'
				                    ),
				                    array(
				                        'paramName' => 'p_where',
				                        'datatype'  => 'array'
				                    )
				                    ),
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
				                    	'paramName' => 'row',
				                        'datatype'  => 'array',
				                    )),
				                ),
				            )),
				        ),
				        		        
				        array(
				            'name'       => '_assignData',
				        	'visibility'   => 'private',
				            'parameters' => array(
				                array('name' => 'data'),
				                array('name' => 'row'),
				            ),
				            
				            'body'       => 'foreach( $data as $key => $value )' . "\n" .
				            				'{'."\n\t" .
				            					'if( array_key_exists( $key, $this->fields_list ) )'."\n\t" .
				            						'{'."\n\t\t" .' if (get_magic_quotes_gpc()) $value = stripslashes($value);'.
				            							'$row->{$this->renderujkolumny($key)} = $value;'."\n\t" .
				            						'}'."\n" .
				            				'}'."\n" .
				            				'return $row;',
				            
				            'docblock'   => new Zend_CodeGenerator_Php_Docblock(array(
				                'longDescription' => 'Metoda przypisuje dane przekazane w zmiennej $data do obiektu Zend_Db_Table_Abstract. Metoda zapewnia, �e zostan� przypisane tylko dane o tych indeksach kt�re s� identyczne z kolumnami w tabeli.',
				                'tags'             => array(
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Param(array(
				                        'paramName' => 'data',
				                        'datatype'  => 'array'
				                    ),
									array(
				                        'paramName' => 'row',
				                        'datatype'  => 'Zend_DB_Row'
				                    )		                    
				                    ),
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
				                        'datatype'  => 'Zend_DB_Row',
				                    )),
				                ),
				            )),
				        ),
		
			        // Metoda do zwracania wszystkie rekordy spełniające kryteria
				        array(
				            'name'       => 'selectAll',
				        	'visibility'   => 'public',
				        	'parameters' => array(
				        		array('name' => 'numberOfPages = NULL'."\n							"),
				        		array('name' => 'rowCount = NULL'."\n							"),
				        		array('name' => 'p_where = array()'."\n							"),
				        		array('name' => 'p_from = array()'."\n							"),
				        		array('name' => 'p_order = array()'."\n							"),
				        		array('name' => 'p_group = array()'."\n							"),
				        		array('name' => 'p_join_left = array()')
				            ),
				            
				            'body' =>  	
				            			'$select = $this->select()->setIntegrityCheck(false);'."\n".
		                				'if (isset($numberOfPages)&&isset($rowCount))'."\n".
		    							'	$select ->limitPage( $numberOfPages, $rowCount );'."\n\n".
		        			
							        	'foreach ($p_from as $value  => $v){'."\n". 
									    '	$this->nazwy_kolumn[] = (string)$value;'."\n". 
									    '	$select->from($value, $this->renderujkolumny($v));'."\n". 
									    '}'."\n\n". 				            
				            
								        'foreach ($p_where as $value){'."\n".        
								        '	$select->where($this->renderujkolumny($value));'."\n".     
								        '}'."\n\n".       
								        
				            			'foreach ($p_join_left as $value  => $v){'."\n".        
								        '	$select->joinLeft($value, $v);'. "\n".    
								        '}'."\n\n".
				            
								        'foreach ($p_order as $value){'."\n".        
								        '	$select->order($this->renderujkolumny($value));'."\n".     
								        '}'."\n\n".
								        
								        'foreach ($p_group as $value){'."\n".        
								        '	$select->group($this->renderujkolumny($value));'."\n".     
								        '}'."\n\n".
								        
				            			'if ($numberOfPages==NULL)'."\n".
				            			'{'."\n".
				            				'$s = $this->fetchAll($select);'."\n".
				            				'if ($s)'."\n".
				            				'{'."\n".
				            				'	return $s->toArray();'."\n".
				            				'}'."\n".
				            				'return $s;'."\n".
				            			'}'."\n".
				            			'else'."\n".
				            				'return $select;'."\n",				            	            
				            
				            'docblock'   => new Zend_CodeGenerator_Php_Docblock(array(
				                'longDescription' => 'Metoda do zwracania wszystkie rekordy spełniające kryteria.',
				                'tags'             => array(     
				            		new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
				                        'datatype'  => 'array',
				                    )),
				                ),
				            )),
				        ),
				        array(
				            'name'       => 'selectOneL',
				        	'visibility'   => 'public',
				        	'parameters' => array(
				        		array('name' => 'p_id'."\n							"),
				        		array('name' => 'p_class_name_lang'."\n							"),
				        		array('name' => 'p_lang_kod'."\n							"),
				            ),
				            'body' =>  	
				            			
				            	    	'$lang = new $p_class_name_lang;'."\n"."\n".
    	
								    	'$ref_list = $this->ref_list;'."\n".
								    	'$p_lang_fk = $lang->fk_list;'."\n"."\n".
								
								    	
								    	'$select = $this->select()->setIntegrityCheck(false)'."\n".
								    	'			 ->from(array(\'p\' => $this->_name), \'*\')'."\n".
								    	'             ->from(array(\'l\' => $lang->_name), \'*\');'."\n"."\n".   	
								    	
								    	'for ($i=0;$i<count($ref_list);$i++)'."\n".
								    	'{'."\n".
								    	'	if ($ref_list[$i]==$lang->_name)'."\n".
								    	'	{'."\n".
								    	'		$select->where(\' l.\'.$this->renderujkolumny($ref_list[$i+1]).\' like p.\'.$this->renderujkolumny($this->PK));'."\n". 				            
								    	'	}'."\n".
								    	'}'."\n"."\n".
				            
				            
								        'for ($i=0;$i<count($p_lang_fk);$i++)'."\n".
								    	'{'."\n".
								    	'	if (strpos($p_lang_fk[$i],\'wersja_jezyk_kod_fk\')!== false)'."\n".
								    	'	{'."\n".
								    	'		$select->where($this->renderujkolumny($p_lang_fk[$i]).\' like '.'\\'.'\'\'.$p_lang_kod.\''.'\\'.'\'\');'."\n".
								    	'	}'."\n".
								    	'}'."\n"."\n".

								    	'$select->where($this->renderujkolumny($this->PK).\' like '.'\\'.'\'\'.$p_id.\''.'\\'.'\'\');'."\n"."\n".
								

				            			'if ($s)'."\n".
				            			'{'."\n".
				            			'	return $s->toArray();'."\n".
				            			'}'."\n".
				            			'return $s;'."\n",				            
				            
				            'docblock'   => new Zend_CodeGenerator_Php_Docblock(array(
				                'longDescription' => 'Metoda pobiera rekord o zadanym id i w odpowiedniej wersji językowej.',
				                'tags'             => array(     
				            		new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
				                        'datatype'  => 'array',
				                    )),
				                ),
				            )),
				        ),
				        array(
				            'name'       => 'selectAllL',
				        	'visibility'   => 'public',
				        	'parameters' => array(
				        		array('name' => 'p_class_name_lang'."\n							"),
				        		array('name' => 'p_lang_kod'."\n							"),
				        		array('name' => 'numberOfPages = NULL'."\n							"),
				        		array('name' => 'rowCount = NULL'."\n							"),
				        		array('name' => 'p_where = array()'."\n							"),
				        		array('name' => 'p_from = array()'."\n							"),
				        		array('name' => 'p_order = array()'."\n							"),
				        		array('name' => 'p_group = array()'."\n							"),
				        		array('name' => 'p_join_left = array()')
				            ),

				            'body' =>  	
				            			'$lang = new $p_class_name_lang;'."\n"."\n".
    	
								    	'$ref_list = $this->ref_list;'."\n".
								    	'$p_lang_fk = $lang->fk_list;'."\n"."\n".
										
				            			'foreach ($p_from as $value  => $v){'."\n". 
									    '	$this->nazwy_kolumn[] = (string)$value;'."\n". 
									    '	$select->from($value, $this->renderujkolumny($v));'."\n". 
									    '}'."\n\n".
								    	
								    	'$select = $this->select()->setIntegrityCheck(false)'."\n".
								    	'			 ->from(array(\'p\' => $this->_name), \'*\')'."\n".
								    	'             ->from(array(\'l\' => $lang->_name), \'*\');'."\n"."\n".   	
								    	
								    	'for ($i=0;$i<count($ref_list);$i++)'."\n".
								    	'{'."\n".
								    	'	if ($ref_list[$i]==$lang->_name)'."\n".
								    	'	{'."\n".
								    	'		$select->where(\' l.\'.$this->renderujkolumny($ref_list[$i+1]).\' like p.\'.$this->renderujkolumny($this->PK));'."\n". 				            
								    	'	}'."\n".
								    	'}'."\n"."\n".
								    	
								        'for ($i=0;$i<count($p_lang_fk);$i++)'."\n".
								    	'{'."\n".
								    	'	if (strpos($p_lang_fk[$i],\'wersja_jezyk_kod_fk\')!== false)'."\n".
								    	'	{'."\n".
								    	'		$select->where($this->renderujkolumny($p_lang_fk[$i]).\' like '.'\\'.'\'\'.$p_lang_kod.\''.'\\'.'\'\');'."\n".
								    	'	}'."\n".
								    	'}'."\n"."\n".
				            
				            			'if (isset($numberOfPages)&&isset($rowCount))'."\n".
		    							'	$select ->limitPage( $numberOfPages, $rowCount );'."\n\n".
		        
								        'foreach ($p_where as $value){'."\n".        
								        '	$select->where($this->renderujkolumny($value));'."\n".     
								        '}'."\n\n".       
								        
				            			'foreach ($p_join_left as $value  => $v){'."\n".        
								        '	$select->joinLeft($value, $v);'. "\n".    
								        '}'."\n\n".
				            
								        'foreach ($p_order as $value){'."\n".        
								        '	$select->order($this->renderujkolumny($value));'."\n".     
								        '}'."\n\n".
								        
								        'foreach ($p_group as $value){'."\n".        
								        '	$select->group($this->renderujkolumny($value));'."\n".     
								        '}'."\n\n".
								        
				            			'if ($numberOfPages==NULL)'."\n".
				            			'{'."\n".
				            				'$s = $this->fetchAll($select);'."\n".
				            				'if ($s)'."\n".
				            				'{'."\n".
				            				'	return $s->toArray();'."\n".
				            				'}'."\n".
				            				'return $s;'."\n".
				            			'}'."\n".
				            			'else'."\n".
				            				'return $select;'."\n",				            
				            
				            'docblock'   => new Zend_CodeGenerator_Php_Docblock(array(
				                'longDescription' => 'Metoda do zwracania wszystkie rekordy spełniające kryteria.',
				                'tags'             => array(     
				            		new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
				                        'datatype'  => 'array',
				                    )),
				                ),
				            )),
				        ),
				        		        		        
				        array(
				            'name'       => 'getLogin',
				        	'visibility'   => 'public',
				            'parameters' => array(
				            ),
				            
				            'body' =>  '$auth = Zend_Auth::getInstance();'."\n".
				            		   '$user = $auth->getIdentity();'."\n\n".
				            		   
				            		   '$usr_id = $user->{admUzyUzytkownicy::uzytkow_id};'."\n".
				            		   '$usr_login = $user->{admUzyUzytkownicy::uzytkow_login};'."\n\n".
				            
				            		   '$table = Array($usr_id,$usr_login);'."\n".
				            		   'return $table;',
				            
				            'docblock'   => new Zend_CodeGenerator_Php_Docblock(array(
				                'longDescription' => 'Metoda zwracajaca w tablicy id i login zalogowanego użytkownika.',
				                'tags'             => array(
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Param(array(
				                        'paramName' => 'id',
				                        'datatype'  => 'int'
				                    )             
				                    ),
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
				                        'datatype'  => 'Zend_DB_Row',
				                    )),
				                ),
				            )),
				        ),
				        // Method passed as concrete instance
				        array(
				            'name'       => 'zDelete',
				        	'visibility'   => 'public',
				            'parameters' => array(
				                array('name' => 'id'),
				            ),
				            
				            'body' =>  'return $this->delete( $this->renderujkolumny($this->PK).\' like '.'\\'.'\'\'.$id.\''.'\\'.'\'\' );',
				            
				            'docblock'   => new Zend_CodeGenerator_Php_Docblock(array(
				                'longDescription' => 'Metoda wykonuje operację DELETE ze zdefiniowanym kluczem głównym. Usuwa rekord o podanej warto�ci w parametrze $id. Zwraca ilo�� usuni�tych rekord�w.',
				                'tags'             => array(
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Param(array(
				                        'paramName' => 'id',
				                        'datatype'  => 'int'
				                    )             
				                    ),
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
				                        'datatype'  => 'Zend_DB_Row',
				                    )),
				                ),
				            )),
				        ),
				        
				        array(
				            'name'       => 'zUpdate',
				        	'visibility'   => 'public',
				            'parameters' => array(
				                array('name' => 'id'),
				                array('name' => 'data'),
				                array('name' => 'p_where = array()')
				            ),
				            
				            'body' =>	
				            			'$select = $this->select();'. "\n".
				            			
				            			'if ($id!=NULL)'."\n".
										'	$select->where( $this->renderujkolumny($this->PK).\' like '.'\\'.'\'\'.$id.\''.'\\'.'\'\' );'."\n\n".
										
				            			'foreach ($p_where as $value){'."\n".        
								        '	$select->where($this->renderujkolumny($value));'."\n".     
								        '}'."\n\n".
				            
				            			'$user_table = $this->getLogin();'."\n\n".
		
				            			'if (isset($this->modd))'."\n".
				            			'{'."\n".
				            			'	$data[ $this->renderujkolumny($this->modd)] = date(\'Y-m-d H:i:s\');'. "\n".
				            			'	$data[ $this->renderujkolumny($this->modp)] = $user_table[1];'. "\n".
				            			'}'."\n".			
				            
										'$s = $this->fetchRow( $select );'."\n".
										'$this->_assignData( $data, $s );'. "\n\n".
										
										'return $s->save();',
				            		
				            
				            'docblock'   => new Zend_CodeGenerator_Php_Docblock(array(
				                'longDescription' => 'Metoda wykonuje operacje UPDATE ze zdefiniowanym jednym kluczem głównym. Zwraca wartość klucza uaktualnianego rekordu.',
				                'tags'             => array(
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Param(array(
				                        'paramName' => 'id',
				                        'datatype'  => 'int'
				                    )             
				                    ),
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
				                        'datatype'  => 'int',
				                    )),
				                ),
				            )),
				        ),
				        array(
				            'name'       => 'zInsert',
				        	'visibility' => 'public',
				            'parameters' => array(
				                array('name' => 'data'),
				            ),
				            
				            'body' =>
				            			'$user_table = $this->getLogin();'."\n\n".
				            			
				            			'if (isset($this->insd))'."\n".
				            			'{'."\n".
				            			'	$data[ $this->renderujkolumny($this->insd)] = date(\'Y-m-d H:i:s\');'. "\n".
				            			'	$data[ $this->renderujkolumny($this->insp)] = $user_table[1];'. "\n".
				            			'	$data[ $this->renderujkolumny($this->modd)] = date(\'Y-m-d H:i:s\');'. "\n".
				            			'	$data[ $this->renderujkolumny($this->modp)] = $user_table[1];'. "\n".
				            			'}'."\n".			
				            
										'$row = $this->createRow();'."\n\n".
		
										'$this->_assignData( $data, $row );'."\n".
										
										'return $row->save();',
		
				            'docblock'   => new Zend_CodeGenerator_Php_Docblock(array(
				                'longDescription' => 'Metoda wykonuje operację INSERT na bazie danych i zwraca lastInserted id.',
				                'tags'             => array(
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Param(array(
				                        'paramName' => 'data',
				                        'datatype'  => 'array'
				                    )
				                    ),
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
				                    	'paramName' => 'lastInsertedId',
				                        'datatype'  => 'int',
				                    )),
				                ),
				            )),
				        ),
				        array(
				            'name'       => 'renderujKolumny',
				        	'visibility'   => 'public',
				            'parameters' => array(
				                array('name' => 'p_ciag')
				            ),
				            
				            'body' =>	
				            			'$ciag_temp = \'\';'."\n".
				            			'if ($this->nazwy_kolumn!=\'\')'."\n".
				            			'{'."\n".
								    	'	foreach ($this->nazwy_kolumn as $tab_nazwa)'."\n".
								        '	{'."\n".
								        '		$ciag_temp = str_replace($tab_nazwa.\'_\',\'\',$p_ciag);'."\n".
								        '	}'."\n".
				            			'}'."\n\n".
    									'if ($ciag_temp!=\'\')'."\n".
    									'	return str_replace($this->_name.\'_\',\'\',$ciag_temp);'."\n".
    									'else'."\n".
    									'	return str_replace($this->_name.\'_\',\'\',$p_ciag);'."\n",
				            						            
				            'docblock'   => new Zend_CodeGenerator_Php_Docblock(array(
				                'longDescription' => 'Metoda wycinająca nazwę tabeli z kolumny',
				                'tags'             => array(
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Param(array(
				                        'paramName' => 'p_ciag',
				                        'datatype'  => 'string'
				                    )             
				                    ),
				                    new Zend_CodeGenerator_Php_Docblock_Tag_Return(array(
				                        'datatype'  => 'string',
				                    )),
				                ),
				            )),
				        ),
				    )
				);    
			      
		      $file = new Zend_CodeGenerator_Php_File(array(
		   
		          'classes'  => array($foo),
		   
		          'docblock' => new Zend_CodeGenerator_Php_Docblock(array(
		  
		              'shortDescription' => 'Klasa mapująca',
		              'tags'             => array(
		                  array(
		                      'name'        => 'license',
		                      'description' => 'New BSD',
		                  ),
		                array(
		                      'name'        => 'copyright',
		                      'description' => 'Information Mastery',
		                  )                  
		              ),
		          )),
		 
		      ));
		      
			createFile2($table_attrs['phpName'].'.php',$file->generate(),$p_path_projekt);
		    }			
		    
		    if ($pdo=='Pdo_Mysql')
			{
	    		for ($i = 0; $i < mysql_num_rows($result); $i++)
				{
					# array wchith contains table attrs
		    		$table_attrs = array();
		    		
		    		# array wchith contains columns
		    		$column = array();		
					# holds single column attrs
		    		$columns_attrs = array();
		    		
					$minod = 0;
					$class_name='';
					$class_name2='';
					$class_name = mysql_tablename($result, $i); 		
		    		
		    		$pos1 = stripos($class_name, '_');
		    		if ($pos1!==false)
					{
						do 
						{			
							$przed = substr($class_name,0,$pos1);
							$duza = substr($class_name,$pos1+1,1);
							$po = substr($class_name,$pos1+2);					
							
							$duza = strtoupper($duza);
							$class_name = $przed.$duza.$po;
							
							$class_name2 = $class_name;
		
							$pos1 = stripos($class_name, '_');
						}
						while ($pos1!==false);
					}
					$class_name2 = str_replace('_','',$class_name2);
		    		
					$table_attrs['name'] = mysql_tablename($result, $i);
					$table_attrs['phpName'] = $class_name2;				
					
					$result2 = mysql_list_fields($this->_db_name,mysql_tablename($result, $i),$link);
					
					//--------Nazwa kolumny--------------//
					$columns = mysql_num_fields($result2);
					
					$szczegoly_kolumn = mysql_db_query($this->_db_name,'SELECT distinct(COLUMN_NAME), UPPER(DATA_TYPE),
																		ifNULL(CHARACTER_MAXIMUM_LENGTH,NUMERIC_SCALE) as \'Dlugosc\', 
																		if(IS_NULLABLE = \'NO\',\'NOT NULL\',\'NULL\') as \'Czy_null\' 
																		  FROM INFORMATION_SCHEMA.COLUMNS
																		  WHERE table_name = \''.mysql_tablename($result, $i).'\'');
					//$szczegoly_kolumn2 = mysql_fetch_array($szczegoly_kolumn);
					
					//--------Sprawdzanie kluczy---------//
					$klucze = mysql_db_query($this->_db_name,"SHOW KEYS FROM ".mysql_tablename($result, $i)." WHERE Key_name = 'PRIMARY'");
					$klucze2 = mysql_fetch_array($klucze);
					//----------------------------------//
					
					//--------Sprawdzanie referencji----//
					$referencje = mysql_db_query($this->_db_name,'SELECT TABLE_NAME, COLUMN_NAME
															  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
															  WHERE REFERENCED_TABLE_SCHEMA = \''.$this->_db_name.'\' and REFERENCED_TABLE_NAME = \''.mysql_tablename($result, $i).'\'');
	
					
					//----------------------------------//
					//--------Sprawdzanie constraintów----//
					$constraint = mysql_db_query($this->_db_name,'SELECT REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME 
															  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
															  WHERE TABLE_SCHEMA = \''.$this->_db_name.'\' and TABLE_NAME = \''.mysql_tablename($result, $i).'\'
															  AND REFERENCED_TABLE_NAME IS NOT NULL');			
					//------------------------------------//
					$licznikfk = 0;
					
					for ($j=0; $j < $columns; $j++)
			    	{		    	
			    		$tablica = explode('_', mysql_field_name($result2, $j));
				    	$czy_specjelny = 0;	    	
				    	
				    	$columns_attrs['name'] = mysql_field_name($result2, $j);
				    	//Dodawanie kolumn specjalnych do modelu
				    	
				    	if ($klucze2[4]!=mysql_field_name($result2, $j))
				    	{
				    		foreach ($tablica as $tab)
					    	{
					    		if ($tab=='insd')
					    		{
					    			$columns_attrs['insd']= mysql_field_name($result2, $j);
					    		}
					    		elseif ($tab=='insp')	
					    		{
					    			$columns_attrs['insp']= mysql_field_name($result2, $j);
					    		}
					    		elseif ($tab=='modd')	
					    		{			    			
					    			$columns_attrs['modd']= mysql_field_name($result2, $j);
					    		}
					    		elseif ($tab=='modp')	
					    		{	
					    			$columns_attrs['modp']= mysql_field_name($result2, $j);		
					    		}
					    	}
				    	}
				    	else
				    		$columns_attrs['primaryKey']= mysql_field_name($result2, $j);				    	
				    	array_push( $column, $columns_attrs );
				    }
					$table_attrs['referencje'] = $referencje;
				    $table_attrs['constrainty'] = $constraint;
				    mysql_free_result($result2);
				    generateModel($table_attrs, $column, $path_projekt, $szczegoly_kolumn);    	
				}
			}
			elseif ($pdo =='Pdo_Pgsql' )
			{
				//echo '<br>wchodzi<br>';
				for ($i = 0; $i < pg_num_rows($pg_lista_tabel); $i++)
				//foreach ($pg_lista_tabel as $pg_table_row)
				{
					//echo $i.'<br>';
					//echo 'tabelki<br>';
					//exit(0);
					# array wchith contains table attrs
					
					$pg_table_row = pg_fetch_row($pg_lista_tabel,$i);
					
					//echo $pg_table_row[0];
					//exit(0);
					
		    		$table_attrs = array();
		    		
		    		# array wchith contains columns
		    		$column = array();		
					# holds single column attrs
		    		$columns_attrs = array();
		    		
					$minod = 0;
					$class_name='';
					$class_name2='';
					$class_name = $pg_table_row[0]; 		
		    		
		    		$pos1 = stripos($class_name, '_');
		    		if ($pos1!==false)
					{
						do 
						{			
							$przed = substr($class_name,0,$pos1);
							$duza = substr($class_name,$pos1+1,1);
							$po = substr($class_name,$pos1+2);					
							
							$duza = strtoupper($duza);
							$class_name = $przed.$duza.$po;
							
							$class_name2 = $class_name;
		
							$pos1 = stripos($class_name, '_');
						}
						while ($pos1!==false);
					}
					$class_name2 = str_replace('_','',$class_name2);
		    		
					$table_attrs['name'] = $pg_table_row[0];
					$table_attrs['phpName'] = $class_name2;				

					//$result2 = mysql_list_fields($this->_db_name,mysql_tablename($result, $i),$link);
					//$result2 = pg_query($pg_link, 'SELECT attname
					//								FROM pg_class, 
					//								     pg_attribute 
					//								WHERE pg_class.relname = \''.$pg_table_row[0].'\' 
					//								AND pg_class.oid = pg_attribute.attrelid
					//								AND pg_attribute.attstattarget = -1
					//								ORDER BY attname');
					
					
					
					//--------Nazwa kolumny--------------//
					//echo 'po kolumnach<br>';
					
					//$columns = pg_num_fields($result2);
					
					//$szczegoly_kolumn = mysql_db_query($this->_db_name,'SELECT distinct(COLUMN_NAME), UPPER(DATA_TYPE),
					//													ifNULL(CHARACTER_MAXIMUM_LENGTH,NUMERIC_SCALE) as \'Dlugosc\', 
					//													if(IS_NULLABLE = \'NO\',\'NOT NULL\',\'NULL\') as \'Czy_null\' 
					//													  FROM INFORMATION_SCHEMA.COLUMNS
					//													  WHERE table_name = \''.mysql_tablename($result, $i).'\'');
					
					$szczegoly_kolumn = pg_query($pg_link, 'SELECT COLUMN_NAME, 
															       upper(DATA_TYPE),
															       COALESCE(character_maximum_length,numeric_scale) AS Dlugosc,
															       CASE WHEN is_nullable = \'NO\' THEN \'NOT_NULL\' ELSE \'NULL\' END AS Czy_null 
															FROM information_schema.columns 
															WHERE table_name =\''.$pg_table_row[0].'\'  ');
					
					//$columns = pg_num_fields($szczegoly_kolumn);
					$result2 = pg_num_rows($szczegoly_kolumn);
					//$szczegoly_kolumn2 = mysql_fetch_array($szczegoly_kolumn);
					
					//--------Sprawdzanie kluczy---------//
					//$klucze = mysql_db_query($this->_db_name,"SHOW KEYS FROM ".mysql_tablename($result, $i)." WHERE Key_name = 'PRIMARY'");
					
					$klucze = pg_query($pg_link, 'SELECT cu.column_name, 
														CASE c.contype
														WHEN \'c\' THEN \'CHECK\'
														WHEN \'f\' THEN \'FOREIGN KEY\'
														WHEN \'p\' THEN \'PRIMARY KEY\'
														WHEN \'u\' THEN \'UNIQUE\'
														END AS "constraint_type"
														FROM pg_constraint c
														LEFT JOIN pg_class t  ON c.conrelid  = t.oid
														LEFT JOIN pg_class t2 ON c.confrelid = t2.oid,
														information_schema.constraint_column_usage cu
														WHERE t.relname = \''.$pg_table_row[0].'\'
														  AND c.contype = \'p\'
														  and c.conname = cu. constraint_name');
					
					$klucze2 = pg_fetch_array($klucze);
					
					
					//----------------------------------//
					
					//--------Sprawdzanie referencji----//
					//$referencje = mysql_db_query($this->_db_name,'SELECT TABLE_NAME, COLUMN_NAME
					//										  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
					//										  WHERE REFERENCED_TABLE_SCHEMA = \''.$this->_db_name.'\' and REFERENCED_TABLE_NAME = \''.mysql_tablename($result, $i).'\'');
		
					$referencje = pg_query($pg_link, 'SELECT tc.constraint_name,
															tc.constraint_type,
															tc.table_name,
															kcu.column_name,
															tc.is_deferrable,
															tc.initially_deferred,
															rc.match_option AS match_type,
															rc.update_rule AS on_update,
															rc.delete_rule AS on_delete,
															ccu.table_name AS references_table,
															ccu.column_name AS references_field
														FROM information_schema.table_constraints tc
														LEFT JOIN information_schema.key_column_usage kcu
														ON tc.constraint_catalog = kcu.constraint_catalog
														AND tc.constraint_schema = kcu.constraint_schema
														AND tc.constraint_name = kcu.constraint_name
														LEFT JOIN information_schema.referential_constraints rc
														ON tc.constraint_catalog = rc.constraint_catalog
														AND tc.constraint_schema = rc.constraint_schema
														AND tc.constraint_name = rc.constraint_name
														LEFT JOIN information_schema.constraint_column_usage ccu
														ON rc.unique_constraint_catalog = ccu.constraint_catalog
														AND rc.unique_constraint_schema = ccu.constraint_schema
														AND rc.unique_constraint_name = ccu.constraint_name
														where ccu.table_name = \''.$pg_table_row[0].'\' ');
					
					
					//----------------------------------//
					//--------Sprawdzanie constraintów----//
					//$constraint = mysql_db_query($this->_db_name,'SELECT REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME 
					//										  FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
					//										  WHERE TABLE_SCHEMA = \''.$this->_db_name.'\' and TABLE_NAME = \''.mysql_tablename($result, $i).'\'
					//										  AND REFERENCED_TABLE_NAME IS NOT NULL');			
					
					$constraint = pg_query($pg_link, 'SELECT 
													distinct(ccu.table_name) AS references_table,
													ccu.column_name AS references_field, kcu.column_name
													FROM information_schema.table_constraints tc
													LEFT JOIN information_schema.key_column_usage kcu
													ON tc.constraint_catalog = kcu.constraint_catalog
													AND tc.constraint_schema = kcu.constraint_schema
													AND tc.constraint_name = kcu.constraint_name
													LEFT JOIN information_schema.referential_constraints rc
													ON tc.constraint_catalog = rc.constraint_catalog
													AND tc.constraint_schema = rc.constraint_schema
													AND tc.constraint_name = rc.constraint_name
													LEFT JOIN information_schema.constraint_column_usage ccu
													ON rc.unique_constraint_catalog = ccu.constraint_catalog
													AND rc.unique_constraint_schema = ccu.constraint_schema
													AND rc.unique_constraint_name = ccu.constraint_name
													WHERE tc.table_name = \''.$pg_table_row[0].'\'
													  AND tc.constraint_type = \'FOREIGN KEY\' ');
					
					//------------------------------------//
					$licznikfk = 0;
					//echo 'przed forem kolumn<br>';
					//
					
					for ($j=0; $j < pg_num_rows($szczegoly_kolumn); $j++)
			    	{		    	
			    		$pg_column_row = pg_fetch_row($szczegoly_kolumn,$j);
			    		
			    		$tablica = explode('_', $pg_column_row[0]);
				    	$czy_specjelny = 0;	    	
				    	//exit(0);
				    	$columns_attrs['name'] = $pg_column_row[0];
				    	//echo $pg_column_row[0].'<br>';
				    	//echo $columns_attrs['name'].'<br>';
				    	//Dodawanie kolumn specjalnych do modelu
				    	//echo $klucze2[0];
				    	if ($klucze2[0]!=$pg_column_row[0])
				    	{
				    		/*
				    		foreach ($tablica as $tab)
					    	{
					    		if ($tab=='insd')
					    		{
					    			$columns_attrs['insd']= $pg_column_row[0];
					    		}
					    		elseif ($tab=='insp')	
					    		{
					    			$columns_attrs['insp']= $pg_column_row[0];
					    		}
					    		elseif ($tab=='modd')	
					    		{			    			
					    			$columns_attrs['modd']= $pg_column_row[0];
					    		}
					    		elseif ($tab=='modp')	
					    		{	
					    			$columns_attrs['modp']= $pg_column_row[0];		
					    		}
					    	}
					    	*/
				    	}
				    	else
				    		$columns_attrs['primaryKey']= $pg_column_row[0];	
				    				    	
				    	//echo $columns_attrs['primaryKey'];
				    	array_push( $column, $columns_attrs );
				    }
					//var_dump($table_attrs);
				    $table_attrs['referencje'] = $referencje;
				    $table_attrs['constrainty'] = $constraint;
				    //pg_free_result($szczegoly_kolumn);
				    
				    generateModel($table_attrs, $column, $path_projekt, $szczegoly_kolumn, $pdo);    	
				}
			}